<template>
  <div class="index-box">
    <div class="content-head">
      <a-row align="middle">
        <a-col span="12">
          <a-button type="primary" icon="plus" style="margin-right: 8px;" @click="() => { $router.push({name:'data_houses_operation',params:{id:'add'}}) }">添加</a-button>
          <a-button type="primary" style="margin-right: 8px;" @click="() => { $router.push({name:'house-import'}) }">导入</a-button>
          <a-button style="margin-right: 8px;" :disabled="$common.isEmpty(selectedRowKeys)" @click="$router.push({name:'data_houses_bz',params:{id:selectedRowKeys.join(',')}})">添加收费标准</a-button>
          <a-popconfirm title="确定要删除当前所选房屋?" @confirm="delHouses()">
            <a-button :disabled="$common.isEmpty(selectedRowKeys)">删除</a-button>
          </a-popconfirm>
        </a-col>
        <a-col span="12">
          <a-input-search style="width:250px;float:right;position: static;padding-right: 5px" placeholder="请输入房号" enterButton @search="onSearch($event,2)"/>
          <a-select style="width:250px;float:right;position: static;" :options="communityList" @change="onSearch($event,1)" placeholder="请选小区" />
        </a-col>
      </a-row>
    </div>
    <div class="content-body">
      <s-table ref="table" :columns="columns" :pageURI='true' :data="dataSource" :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }" rowKey="id" :loading="loading">
        <template slot="operation" slot-scope="text,record">
          <a-dropdown>
            <a class="ant-dropdown-link" href="javascript:void(0);">操作 <a-icon type="down" /></a>
            <a-menu slot="overlay" @click="operation($event,record)">
              <a-menu-item key="1">详情</a-menu-item>
              <a-menu-item key="2">绑定住户</a-menu-item>
              <a-menu-item key="3">添加收费标准</a-menu-item>
              <a-menu-item key="4">编辑</a-menu-item>
              <a-menu-item key="5">
                <a-popconfirm title="确定要删除当前所选房屋?" @confirm="delHouses([record.id])">
                  <a href="javascript:void(0);">删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </template>
      </s-table>
    </div>
    <a-modal title="绑定住户" v-model="bindUserModal" :confirmLoading="bindUserModalLoading" :afterClose="() => { form.resetFields(); }" @ok="handleSubmit">
      <a-form :form="form" @submit="handleSubmit">
        <a-form-item label="所属小区" :labelCol="{xs:{span:24},sm:{span:6}}" :wrapperCol="{xs:{span:24},sm:{span:16}}">
          <span>{{bd_info_name}}</span>
        </a-form-item>
        <a-form-item label="选择住户" :labelCol="{xs:{span:24},sm:{span:6}}" :wrapperCol="{xs:{span:24},sm:{span:16}}" extra="请选择要绑定的住户">
          <a-select placeholder="输入住户身份证号进行搜索" @focus="clearUserList" @search="getBindUserList" :notFoundContent="fetching ? undefined : '无匹配结果'" allowClear showSearch optionFilterProp="children" v-decorator="['house_user_id',{rules:[{required:true,message:'请选择住户'}],initialValue:undefined}]" >
            <a-spin v-if="fetching" slot="notFoundContent" size="small" />
            <a-select-option v-for="item in bindUserList" :key="item.value">{{item.label}}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="身份" :labelCol="{xs:{span:24},sm:{span:6}}" :wrapperCol="{xs:{span:24},sm:{span:16}}">
          <a-select :options="typeList" placeholder="请选择住户身份" v-decorator="['type',{rules:[{required:true,message:'请选择住户身份'}],initialValue:undefined}]"/>
        </a-form-item>
        <a-form-item label="有效期" :required="true" :labelCol="{xs:{span:24},sm:{span:6}}" :wrapperCol="{xs:{span:24},sm:{span:16}}">
          <a-input-group class="ant-input-group-compact">
              <a-form-item :style="{width:'75%',marginRight:'16px'}" v-show="timeIsShow == false">
                <a-date-picker :style="{width:'100%'}" placeholder="请选择住户有效期" :disabledDate="(current) =>  current && current < moment().endOf('day') " v-decorator="['time']"/>
              </a-form-item>
              <a-form-item>
                <a-checkbox @change="({target:{checked}}) => {
                  timeIsShow = checked;
                  if(checked === true) form.resetFields('time');
                }" v-decorator="['long',{initialValue:false}]">长期</a-checkbox>
              </a-form-item>
          </a-input-group>
        </a-form-item>
        <a-form-item style="display: none;">
          <a-input type="hidden" v-decorator="['houses_id',{rules:[{required:true,message:'房屋id不可为空'}],initialValue:''}]"></a-input>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
  import { ACCESS_TOKEN } from '@/store/mutation-types'
  import {STable} from '@/components'
  import moment from 'moment'
  export default {
    name: 'data_houses_index',
    data() {
      return {
        moment,
        token:this.$ls.get(ACCESS_TOKEN),
        loading:false,
        bindUserModal:false,
        communityList:[],
        bindUserModalLoading:false,
        bd_info_id:'', // 小区id
        bd_info_name:'', // 所属小区
        bindUserList:[], // 住户数据
        fetching:false,
        typeList: [{ label: '业主本人', value: 1 }, { label: '亲属', value: 2 }, { label: '租客', value: 3 }, { label: '朋友', value: 4 }, { label: '同事', value: 5 }, { label: '保姆', value: 6 }, { label: '司机', value: 7 }, { label: '装修人员', value: 8 }, { label: '其它', value: 9 }], // 住户身份数据
        timeIsShow:false,
        form:this.$form.createForm(this),
        columns:[
          {
            title:'房屋编号',
            dataIndex:'id',
          },
          {
            title: '小区',
            dataIndex:'bd_info_name',
          },
          {
            title: '楼宇',
            dataIndex:'building_name',
          },
          {
            title: '单元号',
            dataIndex:'unit_name',
          },
          {
            title: '所在楼层',
            dataIndex:'floor'
          },
          {
            title: '房号',
            dataIndex:'houses_name'
          },
          {
            title: '户数',
            dataIndex:'num'
          },
          {
            title:'公摊费系数',
            dataIndex:'ratio'
          },
          {
            title: '收费标准个数',
            dataIndex:'bz_number'
          },
          {
            title: '建筑面积',
            dataIndex:'area',
          },
          {
            title: '房屋类型',
            dataIndex:'houses_type_text'
          },
          {
            title: '投票权数',
            dataIndex:'weights'
          },
          {
            title: '操作',
            dataIndex:'operation',
            scopedSlots:{customRender:'operation'}
          }
        ],
        cur_page:0,
        queryParam:{},
        dataSource:parameter => {
          this.cur_page=parameter.pageNo
          return this.housesList(Object.assign(parameter, this.queryParam))
            .then(res => {
              return res
            })
        },
        selectedRowKeys: [],
        id:''
      }
    },
    components:{STable},
    created() {
      const { id,pageNo} = this.$route.params;
      this.id = id === 'all' ? 0 : id;
      if(!isNaN(this.id)){

      }else {this.$router.go(-1);}
      // if(!isNaN(pageNo)){
      //   this.queryParam.pageNo=pageNo;
      // }
      
    },
    mounted() {
      this.getCommunity();
    },
    methods:{
      // 房屋列表
      housesList(param) {
        return new Promise((resolve, reject) => {
          this.loading = true;
          this.axios({
            method:'post',
            url:'/houses/housesList',
            data:Object.assign(param,{token:this.token,building_id:this.id})
          }).then(res => {
            resolve(res.data);
          }).catch(err => {
            this.$message.error('服务器发生错误...',2);
          }).finally(() => {
            this.loading = false;
          });
        });
      },
      getCommunity() {
        this.axios({
          method:'post',
          url:'/parking/getAllCommunityList',
          data:{token:this.token}
        }).then(res => {
          if(res.code === 0){
              let ifo = {value:0,label:'所有小区'};
              res.data.unshift(ifo);
            this.communityList = res.data;
          }else this.$message.warning(res.msg);
        }).catch(err => {
          this.$message.error('服务器发生错误...');
        })
      },
      // 房屋筛选
      onSearch(val,type) {
        if(type == 1) {
            this.queryParam['bd_info_id'] = val;
        }else{
          this.queryParam['name'] = val;
          this.$refs.table.refresh(true);
        }
      },
      // table选择事件
      onSelectChange (selectedRowKeys) {
        this.selectedRowKeys = selectedRowKeys
      },
      // 删除房屋
      delHouses(ids = this.selectedRowKeys) {
        this.axios({
          method:'post',
          url:'/houses/delHouses',
          data:{token:this.token,ids:ids},
        }).then(res => {
          if(res.code === 0){
            this.$message.success(res.msg,2);
            this.$refs.table.refresh();
          }else this.$message.warning(res.msg,2);
        }).catch(err => {
          this.$message.error('服务器发生错误...',2);
        })
      },
      // 房屋操作
      operation({ key },info) {
        const _this = this;
        _this.bd_info_name = info.bd_info_name;
        _this.bd_info_id = info.bd_info_id;
        if(key === '1') _this.$router.push({name:'data_houses_detail',params:{id:info.id,all_id:this.id,cur_page:this.cur_page}});
        if(key === '2') {
          _this.bindUserModal = true;
          _this.$nextTick(() => {
            _this.form.setFieldsValue({houses_id:info.id});
          });
        }
        if(key === '3') _this.$router.push({name:'data_houses_bz',params:{id:String(info.id)}});
        if(key === '4') _this.$router.push({name:'data_houses_operation',params:{id:info.id}});
      },
      // 确定提交
      handleSubmit(e) {
        e.preventDefault();
        this.form.validateFields((err, values) => {
          if (err) {
            for (let key in err) {
              for (let item of err[key]['errors']) return this.$message.warning(item['message'], 2)
            }
          }
          if(values.long === false && this.$common.isEmpty(values.time)) this.$message.warning('有效期不可为空', 2);
          Object.assign(values,{token:this.token,long:values.long ? 1 : 0,time:this.$common.isEmpty(values.time) ? undefined : values.time.format('YYYY-MM-DD')});
          this.bindUserModalLoading = true;
          this.axios({
            method: 'post',
            url: '/houses/bindUser',
            data: values
          }).then(res => {
            if (res.code == 0) {
              this.$message.success('绑定成功', 1)
              this.bindUserModal = false;
            } else this.$message.warning(res.msg)
          }).catch(() => {
            this.$message.error('服务器发生错误...', 2);
          }).finally(() => {
            this.bindUserModalLoading = false;
          })
        })
      },
      clearUserList(){
        this.bindUserList = [];
      },
      // 获取绑定住户列表
      getBindUserList(value) {
        if(value && value.length > 1){
          this.fetching = true;
          this.axios({
            method:"post",
            url:"/houses/getBindUserList",
            data:{id:this.form.getFieldValue('houses_id'),bd_info_id:this.bd_info_id,token:this.token,text:value,type:1}
          }).then(res => {
            if(res.code==0){
              this.bindUserList = res.data;
            }else{
              this.bindUserList = [];
              this.$message.error(res.msg);
            }
          }).catch(err => {
            this.$message.error('服务器发生错误...');
          }).finally(() => {
            this.fetching = false;
          })
        }else this.bindUserList = [];
      }
    }
  }
</script>

<style lang="less" scoped>
  .index-box{
    background: #ffffff;
    padding: 25px;
    box-sizing: border-box;
    .content-body{
      padding-top:20px;
    }
    .ant-input-group-compact{

    }
  }
</style>